<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>显示名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="昵称或名字"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>手机号：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.mobile"
                        clearable
                        placeholder="手机号"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>职位：</label>
                <div class="table-query-input">
                    <el-cascader
                        v-model="queryData.positionId"
                        v-loading="positionList == null"
                        :show-all-levels="false"
                        clearable
                        filterable
                        :props="{
                            value: 'id',
                            label: 'name',
                            emitPath: false,
                            disabled: 'edit',
                            checkStrictly: true
                        }"
                        :options="positionList"
                    ></el-cascader>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="go('./add')"
            >新增操作员
            </el-button>
            <!-- <el-button
                type="danger"
                plain
                style="margin-bottom: 2em"
                icon="el-icon-delete-solid"
                :disabled="selectDisable"
                >批量删除</el-button
            > -->

            <el-button
                type="warning"
                style="margin-bottom: 2em"
                icon="el-icon-lock"
                :disabled="selectDisable"
                @click="batchLock(false)"
            >批量禁用
            </el-button>
            <el-button
                type="info"
                style="margin-bottom: 2em"
                icon="el-icon-unlock"
                :disabled="selectDisable"
                @click="batchLock(true)"
            >批量启用
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="头像"
                    width="80"
                    align="center"
                >
                    <template slot-scope="scope">
                        <el-avatar :src="coverImage(scope.row.header)"
                        >{{ scope.row.name }}
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="昵称（名字）"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    prop="account"
                    label="用户名"
                    width="160"
                ></el-table-column>
                <el-table-column
                    prop="mobile"
                    label="手机号"
                    width="120"
                ></el-table-column>
                <el-table-column prop="positionName" label="职位" width="120">
                    <template slot-scope="scope">
                        <k-tag
                            v-for="(name, index) in scope.row.positionNames"
                            :key="index"
                            :tag="name"
                            text
                        ></k-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="role" label="菜单角色" min-width="100">
                    <template slot-scope="scope" class="no-wrap-text">
                        <k-tag
                            v-for="(name, index) in scope.row.roleNames"
                            :key="index"
                            :tag="name"
                            text
                        ></k-tag>
                    </template>
                </el-table-column>

                <el-table-column
                    prop="loginData.loginTime"
                    label="最后登录时间"
                    width="180"
                >
                </el-table-column>

                <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="scope">
                        <k-tag :tag="userStatus[scope.row.userStatus]"></k-tag>
                    </template>
                </el-table-column>

                <el-table-column
                    label="操作"
                    width="340"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            :loading="scope.row.opLoading"
                            class="error"
                            type="text"
                            size="mini"
                            icon="el-icon-add"
                            @click="clickAddAccount(scope.row,)"
                        >新增登录方式
                        </el-button>
                        <el-button
                            :loading="scope.row.opLoading"
                            class="warning"
                            type="text"
                            size="mini"
                            icon="el-icon-refresh-right"
                            @click="resetPass(scope.row)"
                        >重置密码
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="go('add?id=' + scope.row.id)"
                        >编辑
                        </el-button>
                        <el-button
                            v-if="scope.row.userStatus === 'normal'"
                            :loading="scope.row.opLoading"
                            class="danger"
                            type="text"
                            icon="el-icon-delete"
                            size="mini"
                            @click=" tableDelete(
                                    '/user/cu/admin/user/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true
                                )"
                        >删除
                        </el-button>
                        <el-button
                            v-if="scope.row.userStatus === 'normal'"
                            :loading="scope.row.opLoading"
                            class="warning"
                            type="text"
                            size="mini"
                            icon="el-icon-lock"
                            @click="changeUserStatus(scope.row, false)"
                        >禁用
                        </el-button>
                        <el-button
                            v-if="scope.row.userStatus === 'lock'"
                            :loading="scope.row.opLoading"
                            size="mini"
                            type="text"
                            icon="el-icon-unlock"
                            @click="changeUserStatus(scope.row, true)"
                        >启用
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            :before-close="dialogClose"
            custom-class="one-dialog"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="6em"
                :rules="formRules"
                class="table-edit-from"
            >
                <el-form-item prop="username" label="用户名">
                    <el-input v-model="dataForm.username"></el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input
                        v-model="dataForm.password"
                        type="password"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="checkPass" label="确认密码">
                    <el-input
                        v-model="dataForm.checkPass"
                        type="password"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="addAccount()"
                >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Fetch from "@/api/request.js";
import {TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {treeList2Tree, beanCopy} from "@/utils/index.js";
import {get, put, post} from "@/api/request";
import {checkUsernameExits, putUserNameForLogin} from "@/api/user";

export default {
    name: "AdminUserList",
    components: {},
    mixins: [TablePage],
    data() {
        return {
            queryData: {
                name: "",
                mobile: "",
                role: true,
                position: true,
                positionId: null,
                orders: [
                    {
                        asc: false,
                        column: "created_time"
                    }
                ]
            },
            formRules: {
                username: [
                    {
                        required: true,
                        message: "请输入登录用户名",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value) {
                                checkUsernameExits({
                                    username: value,
                                    userType: "admin"
                                }).then(res => {
                                    if (res) {
                                        callback(new Error("用户名已经存在"));
                                    } else {
                                        callback();
                                    }
                                });
                            }
                        },
                        trigger: "blur"
                    }
                ],
                password: [
                    {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    },
                    {
                        min: 6,
                        max: 20,
                        message: "长度在 6 到 20 个字符",
                        trigger: "blur"
                    }
                ],
                checkPass: [
                    {
                        required: true,
                        message: "请再次输入密码",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value !== this.dataForm.password) {
                                callback(new Error("两次输入密码不一致!"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ]
            },
            positionList: null
        };
    },
    computed: {
        ...mapState({
            userStatus: state => state.status.userStatus,
            adminUserListVersion: state => state.adminUserListVersion,
        })
    },
    watch: {
        adminUserListVersion() {
            this.resetSearch();
        }
    },
    created() {
        this.loadPosition();
    },
    mounted() {
    },
    methods: {
        search(queryData) {
            this.loadTable("/user/cu/admin/user/page", queryData);
        },
        async batchLock(status) {
            if (!status) {
                await this.$confirm("确定禁用这些账号吗？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                });
            }
            this.tableData
                .filter(v => this.tableSelect.includes(v.id))
                .forEach(v => this.changeUserStatus(v, status));
        },
        changeUserStatus(data, status) {
            data.opLoading = true;
            post(`/user/cu/admin/user/enable/${status}/${data.id}`)
                .then(res => {
                    data.userStatus = status ? "normal" : "lock";
                })
                .finally(() => {
                    data.opLoading = false;
                });
        },
        loadPosition() {
            get("/user/cu/admin/position/list").then(res => {
                this.positionList = treeList2Tree(res);
            });
        },
        async resetPass(row) {
            await this.$confirm("确定将密码重置为tk123456吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            });
            post(`/user/cu/user/change/password-admin/${row.id}`, {
                newPassword: "tk123456"
            })
                .then(() => {
                    this.$message.success("重置成功");
                })
                .catch(e => {
                    this.$message.error("重置失败");
                });
        },
        // 添加登录方式
        addAccount() {
            putUserNameForLogin(this.dataForm).then(data => {
                this.dialogFormVisible = false;
                this.$message.success("添加成功")
            })
        },
        clickAddAccount(row) {
            this.dialogFormVisible = true;
            this.dataForm.userId = row.id;
        }
    }
};
</script>

<style lang="scss" scoped></style>
